#include "stdafx.h"
#include "file.h"

MyFile *file_open(const char *filename) {
	MyFile *f;
	FILE *fp;

	if(strncmp(&filename[strlen(filename)-2], ".c", strlen(".c"))) {
		return 0;
	}

	fp = fopen(filename, "rt");
	if(fp == 0)
		return 0;

	f = (MyFile *)malloc(sizeof(MyFile));
	f->file = fp;
	fseek(fp, 0, SEEK_END);
	f->file_size = ftell(fp) / sizeof(char);
	fseek(fp, 0, SEEK_SET);

	return f;
}

void file_close(MyFile *f) {
	if(f) fclose(f->file);
	free(f);
}

void file_read(char *buffer, MyFile *f) {
	int read_size = 0;

	if(f == 0)
		return ;

	while(!feof(f->file)) {
		char buf[256] = { 0, };
		fgets(buf, 256, f->file);
		// buf[strlen(buf)] = '\n';
		strcat(buffer, buf);
	}
}

char *pre_processor(char *source) {
	int exit = 0;
	size_t i;
	char *pre_processed_source = 0;
	
	if(source == 0) return 0;
	pre_processed_source = strstr(source, "main");

	if(pre_processed_source == 0) return 0;

	for(i = 0 ; i < strlen(pre_processed_source), exit < 2 ; ++i) {
		if(*pre_processed_source == '(') {
			exit = 1;
		} else if(*pre_processed_source == ')') {
			exit = 2;
		}
		pre_processed_source++;
	}

	while(pre_processed_source != 0) {
		if(*pre_processed_source == '{') {
			pre_processed_source++;
			// start
			break;
		}
		pre_processed_source++;
	}

	if(exit != 2) {
		pre_processed_source = 0;
	}

	return pre_processed_source;
}
